package com.group4.rbac.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.group4.rbac.entity.User;
import com.group4.rbac.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
public class DBRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //查询校验
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //账号查询
        queryWrapper.eq("username", token.getUsername());
        User user = userService.getOne(queryWrapper);
        if(user == null){
          throw new UnknownAccountException("账号不存在");
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }



}
